package com.hy.admin.controller.pages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

public abstract class PageControllerBase {
	
	public static final int ROLE_ADMIN = 1;
	public static final int ROLE_TEACHER = 2;
	public static final int ROLE_WEIXIN = 3;

	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	
	protected final String getAbsolutelyServerPath(HttpServletRequest request){
		String refererUrl = request.getScheme().concat("://").concat(request.getServerName()); 
		int port = request.getServerPort();
	     if(port>0 && port!=80){
	     	refererUrl = refererUrl.concat(":").concat(port+"");
	     }
	     refererUrl=refererUrl.concat(request.getContextPath());
	     return refererUrl;
	}
	
	protected void saveDefaultAttributes2Model(Model model) {
		String serverPath = getAbsolutelyServerPath(request);
		model.addAttribute("BasePath", serverPath);
		model.addAttribute("cssVersion", "201808142314");//css修改时，强制浏览器刷新
		model.addAttribute("jsVersion", "201808142314");//js修改时，强制浏览器刷新
	}
	
	protected boolean isLogin(int role) {
		HttpSession session = request.getSession();
		Boolean isLogin = (Boolean)session.getAttribute("isLogin");
		if(isLogin == null || !isLogin) return false;
		
		Integer userRole = (Integer)session.getAttribute("userRole");
		return (userRole != null && userRole == role);
	}
	
	protected void markedLogin(String userName, int role) {
		HttpSession session = request.getSession();
		session.setAttribute("isLogin", true);
		session.setAttribute("userName", userName);
		session.setAttribute("userRole", role);
	}
	
	protected void logout() {
		HttpSession session = request.getSession();
		session.removeAttribute("isLogin");
		session.removeAttribute("userName");
		session.removeAttribute("userRole");
		session.removeAttribute("access_token");
	}
	
	abstract protected String getViewPrefix();
	
	protected String makeViewName(String pageName){
        return getViewPrefix().concat(pageName);
    }
}
